package com.service.edu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.service.edu.pojo.Chapter;
import com.service.edu.pojo.Subject;
import com.service.edu.service.ChapterService;
import com.service.edu.service.VideoService;
import com.service.utils.ResultVo;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-09-28
 */
@RestController
@RequestMapping("chapter")
@Api(description="课程章节管理")
public class ChapterController {

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private VideoService videoService;


    @ApiOperation("查询指定课程下的章节及小章信息")
    @GetMapping("{cid}")
    public ResultVo queryByCourseId(@ApiParam(name = "cid",value = "查询指定课程下的章节及小章信息",required = true) @PathVariable String cid){
        //根据课程id查询出所有的章节
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("course_id",cid);
        queryWrapper.orderByAsc("gmt_create");
        List<Chapter> list = chapterService.list(queryWrapper);
        //章节id查询出所属的小节
        for (Chapter chapter : list) {
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("chapter_id",chapter.getId());
            queryWrapper.orderByAsc("gmt_create");
            chapter.setChildren(videoService.list(queryWrapper));
        }
        return ResultVo.ok().data("items",list);
    }
    /**
     * 删除的课程章节信息
     * @param id
     * @return
     */
    @ApiOperation("删除课程章节信息")
    @DeleteMapping("{id}")
    public ResultVo delete(@ApiParam(name = "id",value = "要删除的课程章节ID",required = true) @PathVariable String id){
        boolean b = chapterService.removeById(id);
        if (b){
            return ResultVo.ok();
        }
        return ResultVo.error();
    }

    /**
     * 修改课程章节信息
     * @param chapter
     * @return
     */
    @ApiOperation("修改课程章节信息")
    @PutMapping
    public ResultVo update(@RequestBody Chapter chapter){
        chapter.setGmtModified(new Date());
        boolean b = chapterService.updateById(chapter);
        if (b){
            return ResultVo.ok();
        }
        return ResultVo.error();
    }

    /**
     * 添加课程章节信息
     * @param chapter
     * @return
     */
    @ApiOperation("添加课程章节信息")
    @PostMapping
    public ResultVo save(@RequestBody Chapter chapter){
        chapter.setGmtModified(new Date());
        chapter.setGmtCreate(new Date());
        boolean b = chapterService.save(chapter);
        if (b){
            return ResultVo.ok();
        }
        return ResultVo.error();
    }



}

